#include "classid.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <cjson/cJSON.h>

struct ClassIdIndex {
    char **class_id;
    size_t index_size;
};

static size_t get_file_size(const char *filename) {
    struct stat statbuf;
    if (stat(filename, &statbuf) != 0) {
        exit(-2);
    }
    return statbuf.st_size;
}

ClassIdIndex *readClassIdIndex(const char *file_path) {

    FILE *file = fopen(file_path, "r");
    if (file == NULL) {
        fprintf(stderr, "can't read classId file %s\n", file_path);
        return NULL;
    }

    size_t file_size = get_file_size(file_path);
    printf("index file size: %ld\n", file_size);

    char *buffer = malloc(file_size + 1);
    buffer[file_size] = '\0';

    int count = fread(buffer, 1, file_size, file);
    if (count != file_size) {
        fprintf(stderr, "read entire index file failed, read count: %d\n", count);
        free(buffer);
        return NULL;
    }
    printf("index file read finish\n");
    printf("file content: %s\n", buffer);

    cJSON *json = cJSON_Parse(buffer);
    printf("json parse finish\n");
    if (json == NULL || !cJSON_IsArray(json)) {
        fprintf(stderr, "invalid index json, not a json array\n");
        return NULL;
    }

    printf("check array size\n");
    size_t index_size = cJSON_GetArraySize(json);
    printf("index size: %ld\n", index_size);
    char **real_index = malloc(sizeof(char *) * index_size);
    printf("alloc for string array\n");

    int index = 0;
    cJSON *item = NULL;
    cJSON_ArrayForEach(item, json) {
        if (!cJSON_IsString(item)) {
            fprintf(stderr, "index item is not string\n");

            return NULL;
        };

        size_t item_len = strlen(item->valuestring);
        char *real_string = malloc(item_len + 1);
        real_string[item_len] = '\0';
        strcpy(real_string, item->valuestring);
        real_index[index] = real_string;
        index += 1;
    }

    ClassIdIndex *ret = malloc(sizeof(ClassIdIndex));
    ret->class_id = real_index;
    ret->index_size = index_size;

    cJSON_Delete(json);

    return ret;
}

void freeClassIdIndex(ClassIdIndex *index) {
    if (index == NULL) {
        return;
    }

    for (size_t i = 0; i < index->index_size; ++i) {
        char *str = index->class_id[i];
        free(str);
    }
    free(index->class_id);
    free(index);
}

const char *getClassName(ClassIdIndex *class_id, size_t index) {
    if (index >= class_id->index_size) {
        fprintf(stderr, "class id too big: %ld\n", index);
        return NULL;
    }

    return class_id->class_id[index];
}


